package com.yumeng.framework.auth.security.authentication.sms;

import cn.hutool.core.util.StrUtil;
import com.yumeng.common.cache.SimpleCacheAdapter;
import com.yumeng.framework.auth.security.authentication.custom.CustomAbstractUserDetailsAuthenticationProvider;
import com.yumeng.framework.auth.security.authentication.custom.CustomLoginAbstractAuthenticationToken;
import com.yumeng.framework.auth.security.userdetails.MyAbstractUserDetailsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author wxd
 * @date 2025/4/11 09:16
 */
public class SmsAuthenticationProvider extends CustomAbstractUserDetailsAuthenticationProvider {

    private final MyAbstractUserDetailsService myAbstractUserDetailsService;

    public SmsAuthenticationProvider(MyAbstractUserDetailsService myAbstractUserDetailsService) {
        this.myAbstractUserDetailsService = myAbstractUserDetailsService;
    }

    @Override
    protected UserDetails retrieveUser(String username, CustomLoginAbstractAuthenticationToken authentication) throws AuthenticationException {
        return this.myAbstractUserDetailsService.getUserDetailsByPrincipal(username);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, CustomLoginAbstractAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null || StringUtils.isBlank(authentication.getCredentials().toString())) {
            throw new BadCredentialsException("短信验证码不能为空");
        }
        String phone = authentication.getPrincipal().toString();//手机号
        String smsCode = authentication.getCredentials().toString();//验证码
        String sendSmsCode = SimpleCacheAdapter.getSmsCode(phone);//实际发送的验证码
        if (StrUtil.isEmpty(sendSmsCode)) {
            throw new BadCredentialsException("验证码已经过期或尚未发送，请重新发送验证码");
        }
        if (!smsCode.equals(sendSmsCode)) {
            throw new BadCredentialsException("输入的验证码不正确，请重新输入");
        }
        SimpleCacheAdapter.removeSmsCode(phone);
    }

    @Override
    protected CustomLoginAbstractAuthenticationToken createSuccessAuthenticationToken(Object principal, Authentication authentication, UserDetails user) {
        SmsLoginAuthenticationToken result = SmsLoginAuthenticationToken.authenticated(principal,
                authentication.getCredentials(), getAuthoritiesMapper().mapAuthorities(user.getAuthorities()));
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsLoginAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
